import tkinter as tk
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk


def open_image():
    global img_label
    file_path = askopenfilename(filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.bmp")])
    if file_path:
        image = Image.open(file_path)
        photo = ImageTk.PhotoImage(image)
        img_label.config(image=photo)
        img_label.image = photo  # 防止图片被垃圾回收
        # 根据图片尺寸调整窗口大小
        root.geometry(f"{image.width}x{image.height}")


root = tk.Tk()

# 获取屏幕宽度和高度
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# 初始设置一个较小的默认窗口大小（避免无图时窗口过大或过小异常）
root.geometry("100x100")

# 计算窗口在屏幕居中的坐标位置
x = (screen_width - 100) // 2
y = (screen_height - 100) // 2

# 设置窗口的初始位置使其居中
root.geometry(f"+{x}+{y}")

btn = tk.Button(root, text="打开图片", command=open_image)
btn.pack()

img_label = tk.Label(root)
img_label.pack()

root.mainloop()